#第四次作业升级购物车

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price


class Member:
    def __init__(self, level):
        self.level = level  # 会员等级：普通、银牌、金牌、钻石

    @property
    def discount_rate(self):
        """根据会员等级返回折扣率"""
        rates = {
            "普通": 1.0,
            "银牌": 0.9,
            "金牌": 0.8,
            "钻石": 0.7
        }
        return rates.get(self.level, 1.0)


class CartItem:
    def __init__(self, product, qty, member=None):
        self.product = product
        self.qty = qty
        self.member = member or Member("普通")  # 默认是普通会员

    def subtotal(self):
        """计算商品小计（含折扣）"""
        base_price = self.product.price * self.qty
        return base_price * self.member.discount_rate


class ShoppingCart:
    def __init__(self):
        self.items = []

    def add(self, product, qty=1, member=None):
        self.items.append(CartItem(product, qty, member))

    def base_total(self):
        """计算原价总金额"""
        return sum(item.product.price * item.qty for item in self.items)

    def discounted_total(self):
        """计算折扣后总金额"""
        return sum(item.subtotal() for item in self.items)

    def total_discount(self):
        """计算总折扣金额"""
        return self.base_total() - self.discounted_total()

    def show(self):
        print("-" * 40)
        for item in self.items:
            member_info = f"[{item.member.level}会员]" if item.member.level != "普通" else ""
            print(
                f"{item.product.name} ×{item.qty}\t原价:￥{item.product.price * item.qty:.2f} {member_info}\t折后:￥{item.subtotal():.2f}")
        print("-" * 40)
        print(f"商品总价：￥{self.base_total():.2f}")
        print(f"会员折扣：-￥{self.total_discount():.2f}")
        print(f"应付总额：￥{self.discounted_total():.2f}")


# --- 测试 ---
if __name__ == "__main__":
    # 创建商品
    apple = Product("苹果", 3.5)
    bread = Product("面包", 4.0)
    milk = Product("牛奶", 6.0)

    # 创建购物车
    cart = ShoppingCart()

    # 添加商品（不同会员等级）
    cart.add(apple, 4, Member("普通"))  # 普通会员无折扣
    cart.add(bread, 2, Member("银牌"))  # 银牌会员9折
    cart.add(milk, 3, Member("钻石"))  # 钻石会员7折

    # 显示购物车
    cart.show()